# Author:   Lemene
# License:  Public Domain - free to do as you wish

import pickle
import pyDes as des
import shutil,os

def loadPgw(key):
    f = open("pgw", "rb")
    print(f.read())

def makeKey(key):
    
    while len(key) < 24:
        key = '0'.join([key, key])

    k1 = des.des(key[0:8])
    k2 = des.des(key[8:16])
    k3 = des.des(key[16:24])
    return (k1,k2,k3)
    
def savePgw(data, key):
    bstr = pickle.dumps(data)

    (k1,k2,k3) = makeKey(key)
    
    e1 = k1.encrypt(addTail(bstr))
    e2 = k2.decrypt(e1)
    e3 = k3.encrypt(e2)

    if os.path.exists("pgw"):
        shutil.copy("pgw", "pgw.bak")        
    
    with open("pgw", "wb") as f:
        f.write(e3)

def loadPgw(key):
    with open("pgw", "rb") as f:
        bstr = f.read()

    (k1,k2,k3) = makeKey(key)

    d3 = k3.decrypt(bstr)
    d2 = k2.encrypt(d3)
    d1 = k1.decrypt(d2)

    return pickle.loads(removeTail(d1))
    
def addTail(bstr):
    tailLen = 8 - len(bstr) % 8

    tail = b'a000000000'
    return bstr + tail[0:tailLen]

def removeTail(bstr):
    for i in range(len(bstr)):
        if bstr[-1-i] == b'0'[0]:
            continue
        elif bstr[-1-i] == b'a'[0]:
            return bstr[0:-1-i]
        else:
            raise "str has no tail"
    raise "str has no tail"
